// API服务模块，封装所有的请求接口

/**
 * 封装云函数调用方法
 * @param {String} name 云函数名称
 * @param {Object} data 请求数据
 * @param {Boolean} needToken 是否需要token
 */
const request = (name, data = {}, needToken = true) => {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: "加载中...",
      mask: true,
    });

    console.log("调用云函数参数:", { name, data });

    // 调用云函数
    wx.cloud.callFunction({
      name: name,
      data: {
        type: data.type,
        data: data.data,
      },
      success: (res) => {
        console.log("云函数返回原始数据:", res);
        wx.hideLoading();

        // 处理返回数据
        if (res.result) {
          console.log("云函数返回结果:", res.result);
          if (res.result.code === 200) {
            resolve(res.result);
          } else {
            reject({
              success: false,
              message: res.result.msg || "请求失败",
              data: res.result.data,
            });
          }
        } else {
          console.error("云函数返回结果为空");
          reject({
            success: false,
            message: "云函数返回数据为空",
            data: null,
          });
        }
      },
      fail: (err) => {
        console.error("云函数调用失败:", err);
        wx.hideLoading();
        wx.showToast({
          title: err.errMsg || "网络异常，请重试",
          icon: "none",
        });
        reject(err);
      },
    });
  });
};

// API接口定义
const api = {
  // 获取微信登录SessionID
  getSessionId: (code) => {
    console.log("开始获取sessionId, code:", code);
    return request(
      "quickstartFunctions",
      {
        type: "getSessionId",
        code: code, // 直接传递 code，不要包装在 data 对象中
      },
      false
    );
  },

  // 用户登录
  login: (data) => {
    return request(
      "quickstartFunctions",
      {
        type: "login",
        data: {
          userInfo: data.userInfo,
        },
      },
      false
    );
  },

  // 获取用户信息
  getUserInfo: (refresh = true) => {
    return request(
      "quickstartFunctions",
      {
        type: "getUserInfo",
        data: {
          refresh: refresh,
        },
      },
      true
    );
  },

  // 上传用户头像
  uploadUserAvatar: (filePath) => {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: "上传中...",
        mask: true,
      });

      const token = wx.getStorageSync("token");
      if (!token) {
        wx.hideLoading();
        wx.redirectTo({
          url: "/pages/index/index",
        });
        return reject(new Error("未登录或登录已过期"));
      }

      // 上传到云存储
      wx.cloud.uploadFile({
        cloudPath: `avatars/${Date.now()}-${Math.random()
          .toString(36)
          .slice(-6)}`,
        filePath: filePath,
        success: (res) => {
          // 调用云函数更新头像
          request(
            "quickstartFunctions",
            {
              type: "updateUserAvatar",
              data: { fileID: res.fileID },
            },
            true
          )
            .then(resolve)
            .catch(reject);
        },
        fail: (err) => {
          wx.hideLoading();
          wx.showToast({
            title: "上传失败",
            icon: "none",
          });
          reject(err);
        },
        complete: () => {
          wx.hideLoading();
        },
      });
    });
  },

  // 更新用户信息
  updateUserInfo: (userInfo, verificationCode) => {
    return request(
      "quickstartFunctions",
      {
        type: "updateUserInfo",
        data: {
          userInfo: userInfo,
          verificationCode: verificationCode,
        },
      },
      true
    );
  },

  // 发送手机验证码
  sendVerificationCode: (phoneNumber) => {
    return request(
      "quickstartFunctions",
      {
        type: "sendVerificationCode",
        data: { phoneNumber: phoneNumber },
      },
      true
    );
  },

  // 获取用户健康数据
  getUserHealthData: () => {
    return request(
      "quickstartFunctions",
      {
        type: "getUserHealthData",
      },
      true
    );
  },

  // 获取资讯列表
  getNewsList: (page = 1, pageSize = 10) => {
    return request(
      "quickstartFunctions",
      {
        type: "getNewsList",
        data: {
          page,
          pageSize,
        },
      },
      true
    );
  },

  // 获取菜谱列表
  getRecipeList: (page = 1, pageSize = 10, category = "") => {
    return request(
      "quickstartFunctions",
      {
        type: "getRecipeList",
        data: {
          page,
          pageSize,
          category,
        },
      },
      true
    );
  },

  // 获取菜谱详情
  getRecipeDetail: (recipeId) => {
    return request(
      "quickstartFunctions",
      {
        type: "getRecipeDetail",
        data: {
          recipeId,
        },
      },
      true
    );
  },

  // 获取菜谱分类
  getRecipeCategories: () => {
    return request(
      "quickstartFunctions",
      {
        type: "getRecipeCategories",
      },
      true
    );
  },

  // 搜索菜谱
  searchRecipes: ({ keyword, category, page = 1, pageSize = 10 }) => {
    return request(
      "quickstartFunctions",
      {
        type: "searchRecipes",
        data: {
          keyword,
          category,
          page,
          pageSize,
        },
      },
      true
    );
  },

  // 获取推荐套餐
  getRecommendedMeals: () => {
    return request(
      "quickstartFunctions",
      {
        type: "getRecommendedMeals",
      },
      true
    );
  },
};

const callFunction = async (name, data = {}) => {
  try {
    const result = await wx.cloud.callFunction({
      name,
      data,
    });

    if (!result || !result.result) {
      throw new Error("API调用失败");
    }

    const { success, errMsg, ...rest } = result.result;

    if (!success) {
      throw new Error(errMsg || "API调用失败");
    }

    return rest;
  } catch (error) {
    console.error(`API调用失败 [${name}]:`, error);
    throw error;
  }
};

// 套餐相关接口
const mealApi = {
  // 获取套餐详情
  getMealDetails: (mealId) => {
    return request(
      "quickstartFunctions",
      {
        type: "getMealDetails",
        data: { mealId },
      },
      true
    );
  },
};

// 订单相关接口
const orderApi = {
  // 创建订单
  createOrder: (mealId, quantity = 1) => {
    return request(
      "quickstartFunctions",
      {
        type: "createOrder",
        data: { mealId, quantity },
      },
      true
    );
  },
};

// 测试数据接口
const testApi = {
  // 初始化测试数据
  initTestData: () => {
    return request(
      "quickstartFunctions",
      {
        type: "initTestData",
      },
      true
    );
  },
};

// 修改导出方式，同时导出api和其他API，也添加独立导出
module.exports = api;
// 也兼容按对象访问的方式
module.exports.api = api;
module.exports.mealApi = mealApi;
module.exports.orderApi = orderApi;
module.exports.testApi = testApi;
